package org.deltaset.meta.internal.mockmeta;

import java.util.ArrayList;
import java.util.List;
import org.deltaset.meta.internal.mockmeta.persistence.EntityManager;
import org.deltaset.meta.internal.mockmeta.persistence.PersistenceContext;

/**
 *
 * @author dmakariev
 */
public class BaseRepository {

    private EntityManager entityManager;

    @PersistenceContext
    void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public final Object newEntity(Class entityClass) {
        return newInstance(entityClass);
    }

    public void delete(Class entityClass, Object id) {
        final Object forDelete = entityManager.getReference(entityClass, id);
        entityManager.remove(forDelete);
    }

    public <T> T save(T entity) {
        try {
            final T saved = entityManager.merge(entity);
            return saved;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public <T> T findById(Class<T> entityClass, Object id) {
        final T entity = entityManager.find(entityClass, id);
        if (null == entity) {
            throw new IllegalArgumentException("person with id=" + id + " not found");
        }
        return entity;
    }

    public <T> Long countAll(Class<T> entityClass) {
        return entityManager.createQuery("SELECT count(*) from " + entityClass.getName() + " o", Long.class);
    }

    public <T> List<T> findAll(Class<T> entityClass, Integer firstResult, Integer maxResult) {
        final List<T> founded = entityManager.createQuery("FROM " + entityClass.getName() + " o");
        return new ArrayList<T>(founded);
    }

    private static <T> T newInstance(Class<T> currentClass) {
        try {
            final T newEntity = currentClass.newInstance();
            return newEntity;
        } catch (InstantiationException ex) {
            throw new RuntimeException("could not create " + currentClass.getName(), ex);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException("could not create " + currentClass.getName(), ex);
        }
    }
}
